<template>
  <el-card>
    <div slot="header">
      <h3>开发计划详情-开发完成</h3>
    </div>
    <div class="page-body">
      <DevelopPlanForm
        disabled
        :label-width="labelWidth"
        :data-source.sync="formData"
        :category-path-set="categoryPathSet"
        :user-options="userInfoOptions"
      />
      <DevelopFinishForm ref="finishRef" :label-width="labelWidth" />
      <el-divider content-position="left">开发需求明细</el-divider>
      <el-row>
        <skus-table
          ref="skusTable"
          showSelectCol
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          :selectionChange="TableInfo.setSelection"
        >
          <el-row slot="content_context" type="flex" justify="space-between">
            <BtnRender :render="renderBtnsBar" />
            <div>
              <span v-if="formData.totalOrderFrequency || formData.totalOrderAmount ">合计：</span>
              <span v-if="formData.totalOrderFrequency">{{ formData.totalOrderFrequency }}次</span>
              <span v-if="formData.totalOrderAmount">{{ formData.totalOrderAmount }}元</span>
            </div>
          </el-row>
        </skus-table>
      </el-row>
      <FooterFields :fieldsItems="fieldsItems" :fieldsData="fieldsData" />
    </div>
    <ViewProductDetailsDialog
      :visible.sync="viewProductDetails.visible"
      :req-detail-no="viewProductDetails.reqDetailNo"
    />
  </el-card>
</template>
<script>
import DevelopPlanForm from '../components/DevelopPlanForm';
import DevelopFinishForm from '../components/DevelopFinishForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import FooterFields from '@/pages/commodity/components/FooterFields/DataRender';
import ViewProductDetailsDialog from '../components/ViewProductDetailsDialog';
import { FINISH_TABLE_COLUMNS, FIELDS_ITEMS, getSkuCountCol } from './constants/actionPage';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { TableInfo } from '@/utils/getUtils';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  getDevPlanEditInfoService,
  finishService
} from '@/api/commodity/developmentRequirementPlan/developPlan';
export default {
  components: {
    DevelopPlanForm,
    DevelopFinishForm,
    SkusTable,
    BtnRender,
    FooterFields,
    ViewProductDetailsDialog
  },
  data () {
    return {
      labelWidth: '170px',
      planNo: '', // 计划单号
      formData: {},
      dialogVisible: false, // 供应商考察报告选择弹框开关
      categoryPathSet: [], // categoryPath集合
      userInfoOptions: [],
      TableInfo: new TableInfo({ columns: FINISH_TABLE_COLUMNS, dimensionKey: 'reqDetailNo' }),
      fieldsItems: FIELDS_ITEMS,
      fieldsData: {},
      btnLoading: {
        complete: false,
      },
      viewProductDetails: {
        visible: false,
        reqDetailNo: ''
      }
    }
  },
  mounted () {
    this.TableInfo.setColumns([
      ...FINISH_TABLE_COLUMNS,
      getSkuCountCol(this.handleViewDetails)
    ])
    this.planNo = this.$route?.query?.planNo
    this.loadDevPlanInfo()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnBars = [
        {
          label: '开发完成',
          method: this.handleComplete,
          loading: this.btnLoading.complete,
          disabled: this.TableInfo.isNullList()
        },
        {
          label: '取消开发',
          method: this.handleCancelDevelop,
          disabled: this.TableInfo.isNullSelection()
        },
        { label: '返回', type: 'default', method: this.handleGoBack }
      ]
      return getListPageBtnsBar(h, btnBars)
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'developPlanList' })
    },
    // 取消开发
    handleCancelDevelop () {
      const isInSelection = item => {
        const idKey = this.TableInfo.dimensionKey
        const selectionFlags = this.TableInfo.selection.map(item => item[idKey])
        return selectionFlags.includes(item[idKey])
      }
      this.TableInfo.setList(this.TableInfo.list.map(item => {
        if (isInSelection(item)) return { ...item, cancelFlag: '1', cancelFlagStr: '是' }
        return item
      }))
    },
    // 完成
    async handleComplete () {
      const data = this.getCompleteParams()
      if (!data) return
      const loadingFn = state => { this.btnLoading.complete = state }
      const res = await finishService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('开发完成成功')
        this.handleGoBack()
      }
    },
    // 加载开发详情
    async loadDevPlanInfo () {
      const data = { planNo: this.planNo }
      const res = await getDevPlanEditInfoService(data, '.page-body')
      if (res?.retData) {
        this.TableInfo.setList(res.retData.detailVoList)
        this.setFormDataDetails(res.retData)
        this.fieldsData = res.retData
      }
    },
    // 设置表单详情数据
    setFormDataDetails (retData) {
      const { categoryPathSet, startTime, endTime, developerId, developerName } = retData
      this.formData = {
        ..._.pick(retData,
          [
            'categoryPath', 'brandName', 'devAreaName', 'devAreaId', 'planName',
            'developerName', 'developerId', 'devDeptName', 'devDeptNo', 'note'
          ]),
        devPlanTime: [startTime, endTime]
      }
      this.categoryPathSet = categoryPathSet
      this.userInfoOptions = developerId ? [{ userId: developerId, userName: developerName }] : []
    },
    // 获取完成入参
    getCompleteParams () {
      const results = this.$refs?.finishRef?.getResults()
      if (!results) return
      const canceledReqDetailNos = this.TableInfo.list
        .filter(item => item.cancelFlag == '1' && item.reqDetailNo)
        .map(item => item.reqDetailNo)
      const data = {
        planNo: this.planNo,
        canceledReqDetailNos,
        ...results,
      }
      return data
    },
    // 查看商品详情
    handleViewDetails (row) {
      this.viewProductDetails.visible = true
      this.viewProductDetails.reqDetailNo = row.reqDetailNo
    }
  }
}
</script>
<style lang="less" scoped>
.search-input {
  width: 66%;
}
</style>
